package com.mifengkong.frwidget.update.download;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;

/**
 * Created by WANG on 17/9/13
 */

public class BaseParameter {
    protected boolean retryOnConnectionFailure = true;
    protected int connectTimeout = 30;
    protected int writeTimeout = 30;
    protected int readTimeout = 30;
    protected String url = "";
    protected File mSaveFile;
    protected ProgressResponseListener mProgressListener;
    protected DownloadFailListener mDownloadFailListener;
    protected boolean mDelectedSaveFile = true;

    public void setListener(ProgressResponseListener progressListener, DownloadFailListener mDownloadFailListener) {
        this.mProgressListener = progressListener;
        this.mDownloadFailListener = mDownloadFailListener;

    }

    protected void setUrl(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    public void setSaveAPKFile(String name, Context context, String versionName) {
        this.mSaveFile = getApkDownLoadFile(name, context, versionName);
    }

    public File getSaveAPKFile() {
        return mSaveFile;
    }

    /**
     * 拦截器，用上ProgressResponseBody
     */
    protected Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder()
                    .body(new ProgressResponseBody(originalResponse.body(), mProgressListener, mDownloadFailListener))
                    .build();
        }
    };


    /**
     * 获取要更新的apk的存放目录
     */
    public File getApkDownLoadFile(String name, Context context, String versionName) {
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
        if (sdCardExist) {

            File externalFilesDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            File file = new File(externalFilesDir, name + "_" + versionName + ".apk");
            return file;
        } else {
            File file = new File(context.getFilesDir(), name + "_" + versionName + ".apk");
            return file;
        }
    }
}
